package com.jawmask.android.discover.bean.task;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.location.Address;
import android.util.Log;

import com.jawmask.android.discover.bean.GPSLocation;
import com.jawmask.android.discover.utils.AppConstants.GOOGLE_SEARCH_PLACE_STATUS;
import com.jawmask.android.discover.utils.AppConstants.HTTP_URL;

public class GetUserLocationAddressTask extends BaseDiscoverTask<GPSLocation, Void, Address> {

	private GPSLocation userLocation;

	public GetUserLocationAddressTask(Context context) {
		super(context);
	}

	@Override
	protected URI getRequestURI(GPSLocation... parameters) throws URISyntaxException {
		URI requestUrl = URI.create(HTTP_URL.GOOGLE_GEOCODING_API_URL.httpUrlValue);
		userLocation = parameters[0];

		List<NameValuePair> requestParameter = new ArrayList<NameValuePair>();
		if (userLocation.getAddress() == null) {
			requestParameter.add(new BasicNameValuePair("latlng", userLocation.getLatitude() + "," + userLocation.getLongitude()));
		} else {
			requestParameter.add(new BasicNameValuePair("address", userLocation.getAddress()));
		}
		requestParameter.add(new BasicNameValuePair("sensor", "true"));

		return URIUtils.createURI(requestUrl.getScheme(), requestUrl.getAuthority(), -1, requestUrl.getPath(), URLEncodedUtils.format(requestParameter, HTTP.UTF_8), null);
	}

	protected Address getObjectFromJSON(JSONObject searchResultsJson) throws JSONException {
		String status = searchResultsJson.getString("status");

		if (status.equalsIgnoreCase(GOOGLE_SEARCH_PLACE_STATUS.OK.status)) {
			JSONArray searchResultArray = searchResultsJson.getJSONArray("results");

			Address address = null;
			JSONObject searchResultJson = null;

			if (searchResultArray.length() > 0) {
				address = new Address(Locale.ENGLISH);
				searchResultJson = searchResultArray.getJSONObject(0);

				JSONObject geometry = searchResultJson.getJSONObject("geometry");
				JSONObject location = geometry.getJSONObject("location");

				address.setLatitude(location.getDouble("lat"));
				address.setLongitude(location.getDouble("lng"));
				address.setAddressLine(0, searchResultJson.optString("formatted_address"));
			}
			return address;
		} else if (status.equalsIgnoreCase(GOOGLE_SEARCH_PLACE_STATUS.ZERO_RESULTS.status)) {
			Log.i("My-Test", "searchResultList ZERO_RESULTS = ");
		}
		return null;
	}
}
